package com.wugh.fast.kernel.core.exception;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.wugh.fast.kernel.core.enums.EnumInterface;


/**
 * 说明: 系统异常<p/>
 * 统一使用该框架做异常处理,包括逻辑上处理
 *
 * <pre>
 *      0:             成功
 *      1~499:         fast框架自身异常
 *      500~999:       自定义框架异常
 *      1000~1999:     业务异常
 *      2000~2999:     用户输入业务异常
 * </pre>
 *
 * @author wugh
 * @date 2019-01-18 18:18
 */
public abstract class FastAbstractException extends RuntimeException implements FastExceptionMark {
    /**
     * 错误信息
     * <pre>
     *     如果异常设置异常信息,默认使用枚举的描述
     * </pre>
     */
    private String message;

    public FastAbstractException() {
    }

    public FastAbstractException(String message) {
        super(message);
        this.message = message;
    }

    public FastAbstractException(String message, Throwable cause) {
        super(message, cause);
        this.message = message;
    }

    public FastAbstractException(Throwable cause) {
        super(cause);
    }

    public FastAbstractException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
        this.message = message;
    }


    /**
     * 获取异常枚举
     *
     * @return
     */
    public abstract EnumInterface<Integer> getExceptionEnum();

    @Override
    public Integer getCode() {
        return getExceptionEnum().getCode();
    }

    @Override
    public String getMessage() {
        if (message == null) {
            StringBuilder msg = new StringBuilder(getExceptionEnum().getDesc());
            if (getCause() != null) {
                //有传入原因,则使用desc: cause
                msg.append(':').append(ExceptionUtil.getRootCauseMessage(this.getCause()));
            }
            message = msg.toString();
        }
        return message;
    }
}
